#!/usr/bin/env python
# encoding:utf-8

import os, sys
import csv,re
from liwe.module import LiweModule
from os3.utils.utils import tmpnam

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage

class Newsletter ( LiweModule ):
	def __init__ ( self, liwe ):
		super ( Newsletter, self ).__init__ ( liwe, "newsletter" )

		self.dbm = self.liwe.dbm
		self.base_url = self.cfg.get ( 'base_url', self.liwe.base_url )

	#{{{def send_mail ( self, sender, recivier, subject, html ):
	def send_mail ( self, sender, receivier, subject, html ):

		html = """<html><head><base href="%s"/></head><body>%s</body></html>"""  % ( self.base_url, html )


		msg_root = MIMEMultipart( 'related' )
		msg_root ['From'] = sender
		msg_root ['To'] = receivier 
		msg_root ['Subject'] = subject

		# Encapsulate the plain and HTML versions of the message body in an
		# 'alternative' part, so message agents can decide which they want to display.
		msg_alternative = MIMEMultipart ( 'alternative' )
		msg_root.attach ( msg_alternative )

		#attach plain text
		sanitize = re.compile(r'<[^>]*>')
		body_plain = sanitize.sub ( '', html )
		msg_text = MIMEText( body_plain, _charset = 'utf-8' )
		msg_alternative.attach ( msg_text )

		#attach html
		msg_text =  MIMEText( html, 'html', _charset = 'utf-8' )
		msg_alternative.attach( msg_text )


		message = msg_root.as_string()		
		try:
			m = smtplib.SMTP ( 'localhost' )
			m.sendmail ( sender, receivier , message )
			m.quit()
			return True
		except smtplib.SMTPException as e:
			return False 
		except Exception as e:
			sys.stderr.write ( "Sendmail Exception: %s" % e )
			return False

	#}}}
	#{{{def _parse_csv ( self ):
	def _parse_csv ( self ):
		if not self.liwe.pyhp.uploads: return {}
		f = self.liwe.pyhp.uploads.values() [ 0 ] [ 'file' ]
		try:
			dialect = csv.Sniffer ().sniff ( f.read ( 1024 ) )
			f.seek ( 0 )
			reader = csv.reader ( f, dialect )
			data = [ r for r in reader ]
			return data
		except Exception as e:
			sys.stderr.write ( "\nNEWSLETTER IMPORT ERROR : %s\n" % e )
			return {}
	#}}}
	#{{{ SUBSCRIBER
	#{{{def set_subscriber ( self, id_subscriber = 0, uid = 0, email = '', lastname = '', name = '', localita = '', provincia = '', nazione = '', azienda = '', area = '', bloccato = 0, note = '', gruppo = 0  ):
	def set_subscriber ( self, id_subscriber = 0, uid = 0, email = '', lastname = '', name = '', localita = '', provincia = '', nazione = '', azienda = '', area = '', bloccato = 0, note = '', gruppo = 0, code = ''  ):
		values = {
				'uid' : uid,
				'email' : email,
				'lastname' : lastname,
				'name' : name,
				'localita' : localita,
				'provincia' : provincia,
				'nazione' : nazione,
				'azienda' : azienda,
				'area' : area,
				'bloccato' : bloccato,
				'gruppo' : gruppo,
				'code' : code,
				'note' : note }
		#_subscriber = self.get_subscriber ( id_subscriber = id_subscriber, email =  email );
		#if not _subscriber:
		if not id_subscriber:
			values [ 'created' ] =  '*NOW()'
			self.dbm.insert ( 'newsletter_subscriber', values )
			values [ 'id_subscriber' ] = self.dbm.insert_id ()
		else:
			#self.dbm.update ( "newsletter_subscriber", values, "id_subscriber = %s" % _subscriber [ 'id_subscriber' ] )
			self.dbm.update ( "newsletter_subscriber", values, "id_subscriber = %s" % id_subscriber )
			values [ 'id_subscriber' ] = id_subscriber
		return values
	#}}}
	#{{{def mail_subscribe ( self, id_subscriber = 0, uid = 0, email = '', lastname = '', name = '', localita = '', provincia = '', nazione = '', azienda = '', rels = ''  ):
	def mail_subscribe ( self, id_subscriber = 0, uid = 0, email = '', lastname = '', name = '', localita = '', provincia = '', nazione = '', azienda = '', area = '' ):
		_code = tmpnam ( ext = 'sub' )
		#_url = "%s/ajax.pyhp?action=newsletter.ajax.subscribe_confirm&code=%s" % ( self.base_url , _code )
		_url = "%s/#_page=subscribe,__m=newsletter,code=%s" % ( self.base_url , _code )
		_unsub = "%s/#_page=unsubscribe,__m=newsletter,id_subscriber=%s" % ( self.base_url, id_subscriber )
		_dct = { 'name' : name,
				 'lastname': lastname,
				 'provincia' : provincia,
				 'localita' : localita,
				 'nazione' : nazione,
				 'azienda' : azienda,
				 'area' : area,
				 'href' : _url,
				 'unsub': _unsub
				}
		_id_subscriber = self.set_subscriber ( id_subscriber = id_subscriber, uid = uid, email = email, lastname = lastname, name = name, localita = localita, provincia = provincia, nazione = nazione, azienda = azienda, area = area, code = _code, bloccato = 1 ) [ 'id_subscriber' ]

		sender = self.cfg.get ( "email.sender", "noreply@example.com" )
		message =  self.templates [ 'SITE_REGISTRATION' ] % _dct;
		self.send_mail ( sender, email, "Iscrizione Newsletter", message )

	#}}}
	#{{{ mail_unsubscribe ( id_subscriber )
	def mail_unsubscribe ( self, id_subscriber = 0 ):
		subscriber = self.get_subscriber ( id_subscriber )
		subscriber [ 'href' ] = "%s/#_page=unsubscribe,__m=newsletter,id_subscriber=%s" % ( self.base_url, id_subscriber )
		sender = self.cfg.get ( "email.sender", "noreply@example.com" )
		message =  self.templates [ 'SITE_UNSUBSCRIBE' ] % subscriber;
		email = subscriber [ 'email' ]
		self.send_mail ( sender, email, "Rimozione Newsletter", message )

	#}}}
	#{{{def subscribe_confirm ( self, code = '' ):
	def subscribe_confirm ( self, code = '' ):
		values = { 'code' : '', 'bloccato' : 0 }
		self.dbm.update ( "newsletter_subscriber", values, "code='%s'" % code )
	#}}}
	#{{{def unsubscribe_confirm  ( self, code = '' ):
	def unsubscribe_confirm  ( self, id_subscriber = 0 ):
		self.dbm.delete ( "newsletter_subscriber", "id_subscriber = %s " % id_subscriber )
	#}}}
	#{{{def subscriber_import ( self, id_group = 0, new_group = ''):
	def subscriber_import ( self, id_group = 0, new_group = ''):

		if new_group:
			group = self.set_group ( title =  new_group )
			id_group = group [ 'id_group' ]
	
		rows = self._parse_csv ()
		if not rows: return
		fields = rows.pop ( 0 )
		for r in rows:
			if not r : continue
			self.set_subscriber ( email = r [ 0 ], lastname =  r [ 1 ], name = r [ 2 ], localita = r [ 3 ], provincia = r [ 4 ], nazione = r [ 5 ], azienda = r [ 6 ], area = r [ 6 ], bloccato = r [ 7 ], gruppo = id_group )
		

	#}}}
	#{{{def get_subscriber ( self, id_subscriber = 0 ):
	def get_subscriber ( self, id_subscriber = 0, email = '', uid = 0 ):
		if ( not id_subscriber and not email ) and ( not uid ) :
			return [];
		conds = []
		if ( id_subscriber ): conds.append ( 'id_subscriber = %s' % id_subscriber )
		if ( email ): conds.append ( "email = '%s'" % email )
		if ( uid ) : conds.append ( "uid = %s"  % uid )
		return self.dbm.single_row ( 'newsletter_subscriber' , '*', " and ".join ( conds ) )
	#}}}
	#{{{def del_subscriber ( self, ids = "" ):
	def del_subscriber ( self, ids = "" ):
		ids = ids.split ( "|" )
		str_ids = " ,".join ( ids )
		self.dbm.delete ( "newsletter_subscriber", "id_subscriber IN ( %s )" % str_ids )
	#}}}
	#{{{def list_subscriber ( self, email = '', lastname = '', name = '', localita = '', provincia = '', nazione = '', azienda = '', area = '', bloccato = '', quant = 10, start_point = 0, do_count = 0 ):
	def list_subscriber ( self, email = '', lastname = '', name = '', localita = '', provincia = '', nazione = '', azienda = '', area = '', bloccato = '', gruppo = 0, quant = 10, start_point = 0, do_count = 0 ):
		conds = []
		if email: conds.append ( "email like '%%%s%%'" % email )
		if lastname: conds.append ( "lastname like '%%%s%%'" % lastname )
		if name: conds.append ( "name like '%%%s%%'" % name )
		if localita: conds.append ( "localita like '%%%s%%'" % localita )
		if provincia: conds.append ( "provincia like '%%%s%%'" % provincia )
		if nazione: conds.append ( "nazione like '%%%s%%'" % nazione )
		if azienda: conds.append ( "azienda like '%%%s%%'" % azienda )
		if area: conds.append ( "area like '%%%s%%'" % area )
		if bloccato: conds.append ( "bloccato = '%s'" % bloccato )
		if gruppo: conds.append ( "gruppo = '%s'" % gruppo )
		extras = ''
		tot_rows = self.dbm.count ( 'newsletter_subscriber', 'id_info', ' AND '.join ( conds ) )
		if do_count:
			extras = " LIMIT %s,%s" % ( start_point, quant )


		tables = [ "newsletter_subscriber as sub left join newsletter_group as gr on sub.gruppo = gr.id_group" ]
		fields = [ "sub.id_subscriber", "sub.uid", "sub.email", "sub.lastname", "sub.name", "sub.localita", "sub.provincia", "sub.nazione", "sub.azienda", "sub.area", "sub.bloccato", "sub.bloccato", "sub.gruppo", "gr.title as gr_title", "sub.created"]	
		#resp = self.dbm.all_rows ( 'newsletter_subscriber', '*', ' AND '.join ( conds ), extras = extras )
		resp = self.dbm.all_rows ( tables, fields , conds =  ' AND '.join ( conds ), extras = extras, debug = self.debug () )
		if not resp:
			resp = []
		return { "rows" : resp, "tot_rows" : tot_rows }
	#}}}
	#}}}
	#{{{ INFO
	#{{{def set_info ( self, id_info = 0, title = '', sender = '', subject = '', send_time = '', created =  ):
	def set_info ( self, id_info = 0, title = '', sender = '', subject = '', template = '', send_time = ''  ):
		values = {
					'title' : title,
					'sender' : sender,
					'subject' : subject,
					'template' : template,
					'send_time' : send_time
					}
		if not id_info:
			values [ 'created' ] = '*NOW()'
			self.dbm.insert ( 'newsletter_info', values )
			id_info = self.dbm.insert_id ()
		else:
			self.dbm.update ( "newsletter_info", values, "id_info = %s" % id_info )

		values [ 'id_info' ] = id_info
		return values
	#}}}
	#{{{def get_info ( self, id_info = 0 ):
	def get_info ( self, id_info = 0 ):
		if not id_info:
			self.liwe.set_error ( '1', 'id_info value is not valid' )
			return [];
		res = self.dbm.single_row ( 'newsletter_info' , '*', 'id_info = %s' % id_info )
		res [ 'send_time' ]  = str ( res [ 'send_time' ] )
		return  res

	#}}}
	#{{{def del_info ( self, ids = "" ):
	def del_info ( self, ids = "" ):
		ids = ids.split ( "|" )
		str_ids = " ,".join ( ids )
		self.dbm.delete ( "newsletter_info", "id_info IN ( %s )" % str_ids )
		self.dbm.delete ( "newsletter_rel" , "id_info IN ( %s ) " % str_ids )

	#}}}
	#{{{def list_info ( self, title = '', sender = '', subject = '', localita = '', bloccato = '', quant = 10, start_point = 0, do_count = 0 ):
	def list_info ( self, title = '', sender = '', subject = '', free = -1, quant = 10, start_point = 0, do_count = 0 ):
		conds = []
		if title: conds.append ( "title like '%%s%%'" % title )
		if sender: conds.append ( "sender like '%%s%%'" % sender )
		if subject: conds.append ( "subject like '%%s%%'" % subject )
		if free != -1 : conds.append ( "free = %s" % free )
		extras = ''
		tot_rows = self.dbm.count ( 'newsletter_info', 'id_info', ' AND '.join ( conds ) )
		if do_count:
			extras = " LIMIT %s,%s" % ( start_point, quant )


		resp = self.dbm.all_rows ( 'newsletter_info', '*', ' AND '.join ( conds ), extras = extras, debug = self.debug () )
		if not resp:
			resp = []
		else:
			for r in resp:
				r [ 'send_time' ]  = str ( r [ 'send_time' ] )

		return { "rows" : resp, "tot_rows" : tot_rows }
	#}}}
	#}}}
	#{{{RELATIONS
	#{{{def set_rel ( self, id_subscriber = 0, id_newsletter = 0, code ='' ):
	def set_rel ( self, id_subscriber = 0, id_info = 0, code ='' ):

		values = { 'code' : code }
		_exist = self.get_rel ( id_subscriber, id_info )
		self.pyhp.log.debug ( "NEWSLETTER set_rel %s" % _exist )
		if not _exist :
			values [ 'id_subscriber' ] = id_subscriber
			values [ 'id_info' ] = id_info
			values [ 'created' ] =  '*NOW()'
			self.dbm.insert ( 'newsletter_rel', values )
		else:
			conds = []
			conds.append ( "id_subscriber = %s" % id_subscriber )
			conds.append ( "id_info = %s" % id_info )
			self.dbm.update ( "newsletter_rel", values , " and ".join ( conds ) )
		return values

	#}}}
	#{{{get_rel  id_subscriber = 0, id_info = 0 
	def get_rel ( self, id_subscriber = 0, id_info = 0 ):
		conds = []
		conds.append ( "id_subscriber = %s" % id_subscriber )
		conds.append ( "id_info =%s" % id_info )
		return self.dbm.single_row  ( "newsletter_rel", [ 'id_subscriber', 'id_info', 'code' ] , " and ".join ( conds ) )
	#}}}
	#{{{check_rel ( self, id_subscriber = 0 ):
	def check_rel ( self, id_subscriber = 0, subscriber_only = 0 , id_info = 0 ):
		if not id_subscriber:
			self.liwe.set_error ( '1', 'id_subscriber value is not valid' )
			return [];

		_conds = []
		if subscriber_only: _conds.append ( 'id_subscriber is  not null' )
		if id_info: _conds.append ( 'id_info = %s' % id_info )

		_tables = [ "newsletter_info as i left join newsletter_rel as r on i.id_info = r.id_info and r.id_subscriber = %s" % id_subscriber ]
		_fields = [ "i.free", "i.id_info", "i.title", "r.id_subscriber" ]

		_cur = self.dbm.select  ( tables = _tables, fields = _fields , conds = " and ".join ( _conds ),  debug = self.debug () );
		resp = []
		if not _cur : return resp
		for _r in _cur:
			if not 'id_subscriber' in _r:
				_r [ 'id_subscriber' ] = 0
			resp.append ( _r )
		_cur.close()
		return resp
	#}}}
	#{{{check_info_rel ( self, id_info = 0 ):
	def check_info_rel ( self, id_info = 0, info_only = 0 , id_subscriber = 0 ):
		if not id_info:
			self.liwe.set_error ( '1', 'id_info value is not valid' )
			return [];

		_conds = []
		if info_only: _conds.append ( 'id_info is  not null' )
		if id_subscriber: _conds.append ( 'id_subscriber = %s' % id_subscriber )

		_tables = [ "(newsletter_subscriber as s left join newsletter_rel as r on s.id_subscriber = r.id_subscriber and r.id_info = %(id_info)s ) join newsletter_info info on info.id_info = %(id_info)s" % { 'id_info' : id_info} ]
		_fields = [ "info.free", "s.id_subscriber", "s.lastname" , "s.name", "s.email","s.uid", "r.id_info" ]

		_cur = self.dbm.select  ( tables = _tables, fields = _fields , conds = " and ".join ( _conds ),  debug = self.debug () );
		resp = []
		if not _cur : return resp
		for _r in _cur:
			if not 'id_info' in _r:
				_r [ 'id_info' ] = 0
			resp.append ( _r )
		_cur.close()
		return resp
	#}}}
	#{{{def list_rel ( id_subscriber = 0, id_info = 0 )
	def list_rel ( self, id_subscriber = 0, id_info = 0, code = '' ):
		conds = []
		if id_subscriber: conds.append ( "id_subscriber = %s" % id_subscriber )
		if id_info: conds.append ( "id_info = %s" % id_info )
		if code: conds.append ( "code = '%s'" % code )

		resp = self.dbm.all_rows ( 'newsletter_rel', '*', ' AND '.join ( conds ) )
		if not resp : resp = []

		return resp

	#}}}
	#{{{set_subscriber_rel ( self, id_subscriber = 0, rels ='' ):
	def set_subscriber_rel ( self, id_subscriber = 0, rels ='' ):
		if not id_subscriber:
			self.liwe.set_error ( '1', 'id_subscriber value is not valid' )
			return [];

		self.dbm.delete ( "newsletter_rel", "id_subscriber = %s" % id_subscriber )
		if not rels : return []

		_rels = rels.split ( "|" )
		for rel in _rels:
			self.set_rel ( id_subscriber, rel )

		return[]
	#}}}
	#{{{set_info_rel ( self, id_info = 0, rels ='' ):
	def set_info_rel ( self, id_info = 0, rels ='' ):
		if not id_info:
			self.liwe.set_error ( '1', 'id_info value is not valid' )
			return [];

		if not rels : return []
		self.dbm.delete ( "newsletter_rel", "id_info = %s" % id_info )

		_rels = rels.split ( "|" )
		for rel in _rels:
			self.set_rel ( rel, id_info )

		return[]
	#}}}
	#{{{def del_subscriber_rel ( self, id_subscriber = 0 )
	def del_subscriber_rel ( self, id_subscriber = 0 ):
		self.dbm.delete ( "newsletter_rel" , "id_subscriber = %s" % id_subscriber )
	#}}}
	#}}}
	#{{{ SENT
	#{{{def set_sent ( self, id_sent = 0, id_newsletter = 0, html = '', sent = '' ):
	def set_sent ( self, id_sent = 0, id_info = 0,subject = '', html = '', sent = '', kwargs = '' ):
		values = {	'id_info' : id_info,
					'html' : html,
					'sent' : sent,
					'subject' : subject }
		
		html = self._fix_html ( html )
		#sent mail to test reciviers
		def trova ( val, idx ):
			if val.startswith ( 'lastname_%s' % idx ) or val.startswith ( 'name_%s' % idx ) or val.startswith ( 'email_%s' % idx ):
				return True
			else:
				return False
		emails = []
		for i in range ( 3 ):
			email = dict( [ ( k.split ( "_" ) [ 0 ] ,v ) for k,v in kwargs.iteritems() if trova ( k, i ) ] )
			if email:
				emails.append ( email )
		
		
		for e in emails:
			message = html
			for k,v in e.iteritems():
				str_replace = "{%s}" % k
				message =  message.replace ( str_replace, v ) 
			self.send_mail ( kwargs [ 'sender' ], e [ 'email' ], subject , message )
		


		#fetch all receivers
		conds = []
		receivers = []
		group = [ k.split ( '_' ) [ 1 ] for k,v in kwargs.iteritems() if k.startswith ( 'group' )  and  v != 'false' ]  
		if group:
			conds.append ( "gruppo in ( %s ) " % ','.join ( group ) )

		if ( kwargs [ 'abbonati' ] == '1' ):
			#tutti gli abbonati
			conds.append (  '( gruppo = 0 or gruppo is null ) and uid <> 0 ' )

		if ( kwargs [ 'free' ] == '1' ):
			#tutti gli utenti free
			conds.append ( '( gruppo = 0 or gruppo is null ) and uid = 0 ' )
	
		for c in conds:
			res = self.dbm.all_rows ( "newsletter_subscriber", [ 'id_subscriber' ] , c )
			if res : receivers.extend ( res )	

		if not receivers:
			self.liwe.set_error ( '1', 'mail mandata ad eventuali utenti test ma non salvata: non sono stati trovati utenti tra quelli selezionati' )
			return [];
			
		#Insert in the table newsletter_sent_log, the e-mails to be sent
		if not id_sent:
			values [ 'created' ] = '*NOW()'
			self.dbm.insert ( 'newsletter_sent', values )
			id_sent = self.dbm.insert_id ()
		else:
			self.dbm.update ( "newsletter_sent", values, "id_sent = %s" % id_sent )
		values [ 'id_sent' ] = id_sent

		for rec in receivers:
			self.set_sent_log ( id_subscriber = rec [ 'id_subscriber' ], id_sent = id_sent )

		return values
	#}}}
	#{{{def get_sent ( self, id_sent = 0 ):
	def get_sent ( self, id_sent = 0 ):
		if not id_sent:
			self.liwe.set_error ( '1', 'id_sent value is not valido' )
			return [];
		res = self.dbm.single_row ( 'newsletter_sent_list' , '*', 'id_sent = %s' % id_sent )
		res [ 'send_time' ]  = str ( res [ 'send_time' ] )
		return res
	#}}}
	#{{{def del_sent ( self, ids = "" ):
	def del_sent ( self, ids = "" ):
		ids = ids.split ( "|" )
		str_ids = " ,".join ( ids )
		self.dbm.delete ( "newsletter_sent", "id_sent IN ( %s )" % str_ids )
	#}}}
	#{{{def list_sent ( self, id_newsletter = 0, quant = 10, start_point = 0, do_count = 0 ):
	def list_sent ( self, id_info = 0, quant = 10, start_point = 0, do_count = 0 ):
		conds = []
		if id_info: conds.append ( "id_info = '%s'" % id_info )
		extras = ' ORDER BY sent DESC'
		tot_rows = self.dbm.count ( 'newsletter_sent', 'id_sent', ' AND '.join ( conds ) )
		if do_count:
			extras += " LIMIT %s,%s" % ( start_point, quant )

		resp = self.dbm.all_rows ( 'newsletter_sent_list', '*', ' AND '.join ( conds ), extras = extras )
		if not resp:
			resp = []
		else:
			for r in resp:
				r [ 'send_time' ]  = str ( r [ 'send_time' ] )
		return { "rows" : resp, "tot_rows" : tot_rows }
	#}}}
	#}}}
	#{{{ GROUPS
	#{{{def set_group ( self, id_group = 0, title = '' ):
	def set_group ( self, id_group = 0, title = '' ):
		values = {	'title' : title }
		if not id_group:
			values [ 'created' ] = '*NOW()'
			self.dbm.insert ( 'newsletter_group', values )
			id_group = self.dbm.insert_id ()
		else:
			self.dbm.update ( "newsletter_group", values, "id_group = %s" % id_group, debug = self.debug () )
		values [ 'id_group' ] = id_group
		return values
	#}}}
	#{{{def get_group ( self, id_group = 0 ):
	def get_group ( self, id_group = 0 ):
		if not id_group:
			self.liwe.set_error ( '1', 'id_group value is not valido' )
			return [];
		res = self.dbm.single_row ( 'newsletter_group' , '*', 'id_group = %s' % id_group )
		return res
	#}}}
	#{{{def del_group ( self, ids = "" ):
	def del_group ( self, ids = "" ):
		ids = ids.split ( "|" )
		str_ids = " ,".join ( ids )
		self.dbm.delete ( "newsletter_group", "id_group IN ( %s )" % str_ids )
	#}}}
	#{{{def list_group ( self, quant = 10, start_point = 0, do_count = 0 ):
	def list_group ( self, quant = 10, start_point = 0, do_count = 0 ):
		extras = ''
		tot_rows = self.dbm.count ( 'newsletter_group', 'id_group' )
		if do_count:
			extras = " LIMIT %s,%s" % ( start_point, quant )

		resp = self.dbm.all_rows ( 'newsletter_group', '*', extras = extras )
		if not resp:
			resp = []
		return { "rows" : resp, "tot_rows" : tot_rows }
	#}}}
	#}}}
	#{{{SENT LOG
	def set_sent_log( self, id_subscriber = 0, id_sent = 0 ):
		values = {
			'id_subscriber' : id_subscriber,
			'id_sent' : id_sent,
			'status' : 0
		}
		self.dbm.insert ( 'newsletter_sent_log', values )
		return values
	#}}

	def cron ( self, base_path ):
		#for regular expression
		def do_rep ( m ):
			return m.group ( 1 )
	
		batch_size = int ( self.cfg.get ( "batch_size" , "100" ) )
		conds = []
		conds.append ( "status = 0" )
		conds.append ( "datetime_send <= NOW()" )
		fields = "sender id_sent email name lastname subject html id_subscriber".split ()
		extras = "LIMIT %d" % batch_size

		res = self.dbm.all_rows ( "newsletter_cron", fields, " AND ".join ( conds ), extras = extras )

		if not res: return

		for row in res:
			#ADD UNSUBSCRIBE
			html = re.sub ( '.*<body[^>]*>(.*)<body.*', do_rep , row [ 'html' ] )
			unsub = self.templates [ 'SITE_ATTACH_UNSUBSCRIBE' ] % row
			html += unsub
			html = self._fix_html ( html, base_path )

			for s in [ "name", "lastname" ]:
				str_replace = "{%s}" % s
				html = html.replace ( str_replace, row [ s ] ) 
			self.send_mail ( row [ 'sender' ], row [ 'email' ], row [ 'subject' ], html )

			self.dbm.update ( "newsletter_sent_log", { 'status': 1, 'sent': '*NOW()' }, "id_sent = %d AND id_subscriber = %d" % ( row [ 'id_sent' ], row [ 'id_subscriber' ] ) )



	def _fix_html ( self, html, base_path = None ):

		if not base_path:
			base_path = os.getcwd ()

		cerca = re.compile ( "<!--embedstyle (.*?)-->")
		res = cerca.findall ( html )
		styles = []
		#l'html può contenere più righe con stili da embeddare
		#con la regexp tro liste di stringhe che possono contenere più stili separati da ;
		#la doppia list comprension ricava una lista di stili sopprimendo quelli ripetuti 
		[ [ styles.append ( y ) for y in x.split ( ";" ) if y not in styles ] for x in res ]
		#ricavo lo style dai file
		html_style = ""
		for path in styles:
			_file = open ( os.path.join ( base_path , path ) )
			html_style += _file.read()
			_file.close() 

		#rimuovo i commenti
		html = re.sub (  "<!--embedstyle (.*?)-->","", html )

		html = """<style type="text/css">%s</style>""" % html_style + html

		return html
